编写pwd
pwd 的工作过程
主要流程是 追中链接, 读取目录, 一个目录接着一个目录地沿着数向上追踪, 每步查看 i-node 号, 然后在父目录中查找该 i-node 的名字, 指导达到树的顶端.
- 得到 "." 的 i-node 号 n
- chdir.. (使用 chdir)
- 找到 i-node 号 n 链接的名字 (opendir、readdir、closedir)
重复(直到到达书的顶端)
当 ".." 和 "." 的 i-node 号相同时, 就可以认为已经到达文件树的顶端.
pwd 的一种版本
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> ino_t get_inode(char *); void printpathto(ino_t); void inum_to_name(ino_t, char *, int); int main() { printpathto(get_inode(".")); putchar('\n'); return 0; } void printpathto(ino_t this_inode) { ino_t my_inode; char its_name[BUFSIZ]; if (get_inode("..") != this_inode) { chdir(".."); inum_to_name(this_inode, its_name, BUFSIZ); my_inode = get_inode("."); printpathto(my_inode); printf("/%s", its_name); } } void inum_to_name(ino_t inode_to_find, char * namebuf, int buflen) { DIR *dir_ptr; char *t; struct dirent *direntp; dir_ptr = opendir("."); if (dir_ptr == NULL){ perror("."); exit(1); } while ((direntp = readdir(dir_ptr)) != NULL) if (direntp->d_ino == inode_to_find) { strncpy(namebuf, direntp->d_name, buflen); namebuf[buflen-1] = '\0'; closedir(dir_ptr); return; } fprintf(stderr, "error looking for inum %ld\n", inode_to_find); exit(1); } ino_t get_inode(char *fname) { struct stat info; if (stat(fname, &info) == -1) { fprintf(stderr, "Cannot stat"); perror(fname); exit(1); } return info.st_ino; }
Unix 允许将一个磁盘的存储组织成一个由多棵数相互链接的数. 每个磁盘或磁盘上的每个分区都包含一颗目录属.这些独立的树被链接成一个单一的几乎无缝的树, 这个版本 pwd 碰上了数之间的连接地带, 将无法正确的工作.